package com.epfresh.views;

import android.content.Context;
import android.graphics.Paint;
import android.text.Html;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;

import com.epfresh.R;
import com.epfresh.api.adapter.CommonAdapter;
import com.epfresh.api.adapter.ViewHolder;
import com.epfresh.api.constant.AppPurchaseRouterConstant;
import com.epfresh.api.entity.RequestEntityPurchase;
import com.epfresh.api.entity.RequestTag;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.entity.TagPager;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.universalimageloader.core.ImageLoader;
import com.epfresh.api.utils.LocalDisplay;
import com.epfresh.api.utils.T;
import com.epfresh.api.widget.list.LoadMoreListView;
import com.epfresh.api.widget.ptr.PtrDefaultHandler;
import com.epfresh.api.widget.ptr.PtrFrameLayout;
import com.epfresh.api.widget.ptr.PtrHandler;
import com.epfresh.api.widget.ptr.PtrMdFrameLayout;
import com.epfresh.bean.Ad;
import com.epfresh.bean.ContentEntity;
import com.epfresh.bean.GoodsParameters;
import com.epfresh.bean.HomeCommTag;
import com.epfresh.bean.ListGoods;
import com.epfresh.global.BaseActivity;
import com.epfresh.views.tag.TagCloudView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by wzh on 16-7-5.
 */
public class GoodsListView extends PtrMdFrameLayout {

    public interface OnAdListener {
        public void onAd(List<Ad> ads);
    }

    OnAdListener onAdListener;
    LoadMoreListView lv;
    MultiStateView multiStateView;
    GoodsAdapter adapter;

    List<ListGoods> list = new ArrayList<ListGoods>();
    List<HomeCommTag> tagList = new ArrayList<HomeCommTag>();

    BaseActivity baseActivity;

    AdapterView.OnItemClickListener onItemClickListener;

    TagPager tagPager = new TagPager();
    int PAGE_SIZE = 10;
    GoodsParameters parameters;
    private PtrHandler ptrHandler = new PtrHandler() {
        @Override
        public boolean checkCanDoRefresh(PtrFrameLayout ptrFrameLayout, View view, View view1) {
            return PtrDefaultHandler.checkContentCanBePulledDown(ptrFrameLayout, lv, view1);
        }

        @Override
        public void onRefreshBegin(PtrFrameLayout ptrFrameLayout) {

            refresh();

        }
    };

    private LoadMoreListView.IXListViewListener loadMoreListener = new LoadMoreListView.IXListViewListener() {
        @Override
        public void onLoadMore() {
            loadMore();
        }
    };

    public OnAdListener getOnAdListener() {
        return onAdListener;
    }

    public void setOnAdListener(OnAdListener onAdListener) {
        this.onAdListener = onAdListener;
    }

    public void setOnItemClickListener(AdapterView.OnItemClickListener onItemClickListener) {
        lv.setOnItemClickListener(onItemClickListener);
    }

    public GoodsParameters getParameters() {
        return parameters;
    }

    public void setParameters(GoodsParameters parameters) {
        this.parameters = parameters;
    }

    public GoodsAdapter getAdapter() {
        return adapter;
    }

    public void setAdapter(GoodsAdapter adapter) {
        this.adapter = adapter;
    }

    public GoodsListView(Context context) {
        super(context);
        init();

    }

    public List<HomeCommTag> getTagList() {
        return tagList;
    }

    public void setTagList(List<HomeCommTag> tagList) {
        this.tagList = tagList;
    }

    public GoodsListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public GoodsListView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    public void setHeadView(View v) {
        lv.addHeaderView(v);
    }


    @Override
    protected void initBefore() {
        paddingTop = LocalDisplay.dp2px(15);
        paddingBottom = LocalDisplay.dp2px(15);
    }

    public void init() {
        lv = new LoadMoreListView(getContext());
        lv.setDivider(null);
        lv.setSelector(android.R.color.transparent);
        ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        lv.setLayoutParams(lp);

        multiStateView = new MultiStateView(getContext());
        multiStateView.addView(lv);
        multiStateView.setViewForState(R.layout.loading_view, MultiStateView.VIEW_STATE_LOADING);
        multiStateView.setViewForState(R.layout.empty_goods, MultiStateView.VIEW_STATE_EMPTY);
        multiStateView.setViewForState(R.layout.error_view, MultiStateView.VIEW_STATE_ERROR);
        multiStateView.setOnErrorClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {

                refresh();
            }
        });
        ViewGroup.LayoutParams lp0 = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);

        multiStateView.setLayoutParams(lp0);

        addView(multiStateView);


        adapter = new GoodsAdapter(getContext(), list, R.layout.item_goods_list);
        lv.setAdapter(adapter);

        lv.setXListViewListener(loadMoreListener);
        setPtrHandler(ptrHandler);
    }


    public BaseActivity getBaseActivity() {
        return baseActivity;
    }

    public void setBaseActivity(BaseActivity baseActivity) {
        this.baseActivity = baseActivity;
    }

    public boolean checkCanDoRefresh(PtrFrameLayout ptrFrameLayout, View content, View header) {
        return PtrDefaultHandler.checkContentCanBePulledDown(this, lv, header);
    }

    public void notifyDataSetChanged() {
        adapter.notifyDataSetChanged();
    }

    public void notifyDataSetInvalidated() {
        adapter.notifyDataSetInvalidated();
    }


    public List<ListGoods> getList() {
        return list;
    }

    public void setList(List<ListGoods> list) {
        this.list.clear();
        if (list != null)
            this.list.addAll(list);
    }

    public void clear(){
        this.list.clear();
        this.adapter.notifyDataSetChanged();
    }
/*
    public void initFlags(LinearLayout llTags, ArrayList<HomeCommTag> tags) {
        llTags.removeAllViews();
        int roundRadius = 15; // 8px not dp
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);

        if (tags != null)
            for (int i = 0; i < tags.size(); i++) {
                int flagColor = ColorUtils.parseColor(tags.get(i).getColor());
                TextView flag = new TextView(getContext());
                flag.setLines(1);
                flag.setText(tags.get(i).getName());
                flag.setLines(1);
                flag.setTextSize(9);
                GradientDrawable gd = (GradientDrawable) getResources().getDrawable(R.drawable.btn_flag);
                gd.setCornerRadius(roundRadius);
                lp.setMargins(10, 0, 10, 0);
                flag.setLayoutParams(lp);
                flag.setTextColor(flagColor);
                gd.setStroke(2, flagColor);
                flag.setBackgroundDrawable(gd);
                llTags.addView(flag);
            }
    }*/

    private OnRequestListener onRequestListener = new OnRequestListener<ContentEntity<ListGoods>>() {
        @Override
        public ContentEntity<ListGoods> jsonToObj(String s) {
            Log.e("ESD","条件搜索获取的搜索结果:s="+s);
            return new Gson().fromJson(s, new TypeToken<ContentEntity<ListGoods>>() {
            }.getType());
        }

        @Override
        public void onFail(int i, Object o, Object tag) {
            if (list == null || list.size() == 0) {

                multiStateView.setViewState(MultiStateView.VIEW_STATE_ERROR);
            }
            RequestTag requestTag = (RequestTag) tag;
            updateViewStatus(requestTag);
            if (onAdListener != null) {
                onAdListener.onAd(null);
            }
        }

        @Override
        public void onResponseError(int i, Object o, Object tag) {
            if (list == null || list.size() == 0) {
                multiStateView.setViewState(MultiStateView.VIEW_STATE_ERROR);
            }
            RequestTag requestTag = (RequestTag) tag;
            updateViewStatus(requestTag);
            if (onAdListener != null) {
                onAdListener.onAd(null);
            }
        }

        @Override
        public void onStart(Object o) {

            if (list == null || list.size() == 0) {
                multiStateView.setViewState(MultiStateView.VIEW_STATE_LOADING);
            }
        }

        @Override
        public void onResponse(ResponseEntity<ContentEntity<ListGoods>> responseEntity, Object tag) {


            ContentEntity<ListGoods> responseElement = responseEntity.getResponseElement();
            RequestTag requestTag = (RequestTag) tag;
            if (responseElement != null) {
                List<ListGoods> content = responseElement.getContent();
                List<HomeCommTag> tags = responseElement.getTags();
                if (!parameters.hasType() && tags != null) {
                    tagList.clear();
                    tagList.addAll(tags);
                }
                if (requestTag.action == 0) {
                    list.clear();
                }
                list.addAll(content);
                ///TimeStringUtils.updaTime(list);  todo:2018年11月13日17:14:36

                adapter.notifyDataSetChanged();
                tagPager.setLast(responseElement.getLast());
                Log.d("tagPager", "tagPager:" + tagPager);
                tagPager.setNumber(responseElement.getNumber());
                tagPager.setSize(responseElement.getSize());
                tagPager.setTotalElements(responseElement.getTotalElements());
                if (list.size() == 0) {
                    multiStateView.setViewState(MultiStateView.VIEW_STATE_EMPTY);
                } else {
                    multiStateView.setViewState(MultiStateView.VIEW_STATE_CONTENT);
                }

                if (onAdListener != null) {
                    List<Ad> ads = responseElement.getAds();
                    onAdListener.onAd(ads);
                }
            } else {
                if (list == null || list.size() == 0) {
                    multiStateView.setViewState(MultiStateView.VIEW_STATE_ERROR);
                }
                T.toast("返回数据错误");
                if (onAdListener != null) {
                    onAdListener.onAd(null);
                }
            }
            updateViewStatus(requestTag);
        }
    };

    public void request(GoodsParameters parameters) {

//        if (TextUtils.equals("1",parameters.getType())||TextUtils.equals("2",parameters.getType())){
//
//        }else {
//            parameters.setType(null);
//        }

        RequestEntityPurchase<GoodsParameters> re = new RequestEntityPurchase<>();
        re.setCmd(AppPurchaseRouterConstant.cmd_store_product_list);
        re.setParameters(parameters);
        RequestTag requestTag = new RequestTag();
        requestTag.tag = AppPurchaseRouterConstant.cmd_store_product_list;
        requestTag.action = parameters.getPageNumber();
        baseActivity.request(re, requestTag, onRequestListener);
    }

    public void reload() {
        list.clear();
        adapter.notifyDataSetChanged();
        refresh();

    }

    public void refresh() {
        lv.resetNoMore();
        parameters.setPageSize(PAGE_SIZE);
        parameters.setPageNumber(0);
//        parameters.setFilterCode(parameters.getFilterCode());
        if (TextUtils.equals("1",parameters.getFilterCode())){//现货
            parameters.setType("1");
        }else if (TextUtils.equals("2",parameters.getFilterCode())){//预售
            parameters.setType("2");
        }else {
            parameters.setType(null);
        }
        request(parameters);
    }

    private void loadMore() {
        int number = tagPager.getNumber();
        parameters.setPageSize(PAGE_SIZE);
        parameters.setPageNumber(number + 1);
        request(parameters);
    }

    public void updateViewStatus(RequestTag requestTag) {
        refreshComplete();
        if (tagPager.isLast()) {
            lv.noMore();
        } else {
            lv.stopLoadMore();
        }
    }


    class GoodsAdapter extends CommonAdapter<ListGoods> {

        public GoodsAdapter(Context context, List<ListGoods> runPacks, int a) {
            super(context, runPacks, a);
        }

        @Override
        public void convert(final ViewHolder holder, final ListGoods bean) {
/*            ArrayList<HomeCommTag> tags = bean.getTags();
            initFlags((LinearLayout) holder.getView(R.id.ll_tags), tags);*/
            holder.getView(R.id.tv_now_time).setVisibility(GONE);
            holder.getView(R.id.tv_pre_time).setVisibility(GONE);
            holder.getView(R.id.tv_open_tag).setVisibility(GONE);
            if ("1".equals(bean.getProductParseDto().getType())) {//现售
//                ((TextView) (holder.getView(R.id.tv_now_time))).setText(bean.getPluckingTime());
//                holder.getView(R.id.tv_now_time).setVisibility(VISIBLE);
            }
            if ("2".equals(bean.getProductParseDto().getType())) {//预售
                ((TextView) (holder.getView(R.id.tv_pre_time))).setText("预计" + bean.getDeliveryTime() + "送达");
                holder.getView(R.id.tv_pre_time).setVisibility(VISIBLE);
                holder.getView(R.id.tv_type).setVisibility(View.VISIBLE);
                String html="<font color=\"#00ffffff\">【预售】</font>"+bean.getTitle();
                ((TextView) (holder.getView(R.id.tv_title))).setText(Html.fromHtml(html));
            } else {//现售
                holder.getView(R.id.tv_type).setVisibility(View.GONE);
                ((TextView) (holder.getView(R.id.tv_title))).setText(bean.getTitle());
            }
            holder.getView(R.id.tv_open_tag).setVisibility(GONE);
            String status = bean.getPromotionItemStatus();
            if(status!=null&&"1".equals(status)){
                holder.setText(R.id.tv_open_tag,"即将开始");
                holder.getView(R.id.tv_open_tag).setVisibility(View.VISIBLE);
            }else if(status!=null&&"3".equals(status)){
                holder.setText(R.id.tv_open_tag,"结束了");
                holder.getView(R.id.tv_open_tag).setVisibility(View.VISIBLE);
            }else if(status!=null&&"4".equals(status)){
                holder.setText(R.id.tv_open_tag,"抢光了");
                holder.getView(R.id.tv_open_tag).setVisibility(View.VISIBLE);
            }
            if (bean.getIsAcceptOrders() != 1) {
                holder.setText(R.id.tv_open_tag,"暂不接单");
                holder.getView(R.id.tv_open_tag).setVisibility(View.VISIBLE);
                holder.getView(R.id.tv_now_time).setVisibility(GONE);
                holder.getView(R.id.tv_pre_time).setVisibility(GONE);
            }
            holder.setText(R.id.tv_price, ""+bean.getPriceOnly());
            holder.setText(R.id.tv_price_, "元/"+bean.getUnit());
            double oldPrice = bean.getOriginalPrice();
            holder.getView(R.id.tv_price_old).setVisibility(View.GONE);

            if(oldPrice != bean.getPriceOnly()) {
                holder.setText(R.id.tv_price_old,bean.getOriginalPrice() + "元/" + bean.getUnit());
                holder.getView(R.id.tv_price_old).setVisibility(View.VISIBLE);
                ((TextView)holder.getView(R.id.tv_price_old)).getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
            }
            else{
                holder.getView(R.id.tv_price_old).setVisibility(View.GONE);
            }
            if (!TextUtils.isEmpty(bean.getPack())) {
                if (bean.getName() == null || bean.getName().equals("默认")){
                    holder.setText(R.id.tv_unit_package, bean.getPack());
                }else {
                    holder.setText(R.id.tv_unit_package, bean.getName() + "(" + bean.getPack() + ")");
                }
                holder.getView(R.id.tv_unit_package).setVisibility(VISIBLE);
            } else {
                holder.setText(R.id.tv_unit_package, "");
                holder.getView(R.id.tv_unit_package).setVisibility(GONE);
            }

            ImageLoader.getInstance().displayImage(bean.getThumbnail(), (ImageView) holder.getView(R.id.iv_pic));

            if (bean.getPromotion() != null) {
                String promotionType = bean.getPromotion().getType();
                if ("1".equals(promotionType) || "2".equals(promotionType)) {//1促销2秒杀
                    if (bean.getPromotion().getTagImageUrl() != null && !bean.getPromotion().getTagImageUrl().equals("") && !bean.getPromotion().getTagImageUrl().equals("null")) {
                        holder.getView(R.id.iv_tag).setVisibility(View.VISIBLE);
                        ImageLoader.getInstance().displayImage(bean.getPromotion().getTagImageUrl(), (ImageView) holder.getView(R.id.iv_tag));
                    }
                    else {
                        holder.getView(R.id.iv_tag).setVisibility(View.INVISIBLE);
                    }
                    if ("1".equals(promotionType)) {//1促销2秒杀
                        holder.getView(R.id.tv_activity_promotion).setVisibility(View.VISIBLE);
                        holder.getView(R.id.tv_activity_second).setVisibility(View.GONE);
                    } else if ("2".equals(promotionType)) {//1促销2秒杀
                        holder.getView(R.id.tv_activity_promotion).setVisibility(View.GONE);
                        holder.getView(R.id.tv_activity_second).setVisibility(View.VISIBLE);
                    } else {
                        holder.getView(R.id.tv_activity_promotion).setVisibility(View.GONE);
                        holder.getView(R.id.tv_activity_second).setVisibility(View.GONE);
                    }

                } else {
                    holder.getView(R.id.tv_activity_promotion).setVisibility(View.GONE);
                    holder.getView(R.id.tv_activity_second).setVisibility(View.GONE);
                }
            } else {
                holder.getView(R.id.iv_tag).setVisibility(View.INVISIBLE);
                holder.getView(R.id.tv_activity_promotion).setVisibility(View.GONE);
            }
            ArrayList<HomeCommTag> tags = bean.getTags();
            if (tags != null && tags.size() > 0) {
                TagCloudView tag;
                tag = holder.getView(R.id.ll_tags);
                tag.setVisibility(View.VISIBLE);
                tag.setCommTags(tags);
            } else {
                holder.getView(R.id.ll_tags).setVisibility(View.GONE);
            }
        }
    }

}
